#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPlainTextEdit>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include<QFileDialog>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle("简单的记事本");

    // 获取菜单栏（使用成员变量ui访问）
    QMenuBar* menuBar = this->menuBar();  // 修正变量名大小写一致

    // 添加菜单
    QMenu* menu = new QMenu("文件", this);  // 添加父对象指针
    menuBar->addMenu(menu);

    QAction* action1 = new QAction("打开", this);  // 添加父对象指针
    QAction* action2 = new QAction("保存", this);  // 添加父对象指针
    menu->addAction(action1);
    menu->addAction(action2);

    edit = new QPlainTextEdit(this);  // 添加父对象指针
    QFont font;
    font.setPixelSize(20);
    edit->setFont(font);
    this->setCentralWidget(edit);

    connect(action1,&QAction::triggered,this,&MainWindow::handle1);
    connect(action2,&QAction::triggered,this,&MainWindow::handle2);
}
void MainWindow::handle1()
{
    //先弹出对话框，让用户选择哪个文件打开
    QString path = QFileDialog::getOpenFileName(this);

    //把文件名显示在状态栏中
    QStatusBar* statusbar = this->statusBar();
    statusbar->showMessage(path);
    //创建QFile对象，然后打开文件
    QFile file(path);
    bool ret = file.open(QIODevice::ReadOnly);
    if(!ret)
    {
        statusbar->showMessage(path+"打开失败");
        return;
    }
    //读取文件的内容到text中
    QString text = file.readAll();
    //记得关闭文件
    file.close();
    //将读取到的内容输入到对话框中
    edit->setPlainText(text);

}

void MainWindow::handle2()
{
    QString path = QFileDialog::getSaveFileName(this);
    QStatusBar* statusbar = this->statusBar();
    statusbar->showMessage(path);
    QFile file(path);
    bool ret = file.open(QFile::WriteOnly);
    if(!ret)
    {
        statusbar->showMessage(path+"保存失败");
        return;
    }
    const QString& text = edit->toPlainText();
    file.write(text.toUtf8());
    file.close();
    edit->setPlainText("保存成功");

}
MainWindow::~MainWindow()
{
    delete ui;
}
